#include "swagme.h"
#include "Sprite.h"

Sprite::Sprite(const char *file, const char *shadow) :
    pSpriteSurface(NULL),
    mnNumAnimations(0), mnNumFrames(0)
{
  size_t len = strlen(file);
  SpriteImageFile = new char[len+1];
  if (SpriteImageFile)
    strcpy(SpriteImageFile,file);
  else
    cerr << "Sprite error: SpriteImageFile not allocated\n" << endl;

  pSpriteSurface = IMG_Load(SpriteImageFile);
  if (!pSpriteSurface) {
    cerr << "Sprite error: Unable to load sprite image: %s\n" << SDL_GetError() << endl;
    exit(1);
  }

  if (shadow) {
    len = strlen(shadow);
    ShadowImageFile= new char[len+1];
    if (ShadowImageFile)
      strcpy(ShadowImageFile,shadow);
    else
      cerr << "Sprite error: ShadowImageFile not allocated\n" << endl;
    pShadowSurface = IMG_Load(ShadowImageFile);
    if (!pShadowSurface) {
      cerr << "Sprite error: Unable to load shadow image: %s\n" << SDL_GetError() << endl;
      exit(1);
    }
  } else {
    ShadowImageFile=NULL;
    pShadowSurface=NULL;
  }

  Frame.x=0;
  Frame.y=0;
  Frame.w=SPRITE_SIZE_X;
  Frame.h=SPRITE_SIZE_Y;

  mnNumAnimations = (pSpriteSurface->h) / SPRITE_SIZE_Y;
  mnNumFrames = (pSpriteSurface->w) / SPRITE_SIZE_X;

  cout << "Sprite loaded from '" << SpriteImageFile << "' has " <<
    mnNumAnimations << " animations and " << mnNumFrames << " frames ";
  if (shadow) {
    cout << "with shadow image '" << shadow << "'" << endl;
  } else {
    cout << endl;
  }
}

int Sprite::Blit(SDL_Surface *dst, int x, int y, bool bShadow) {
  int nResult = 0;
  if(bShadow && !pShadowSurface) { return nResult; }
  if (!dst)
    cerr << "Sprite error: invalid destination surface\n" << endl;
  if (!pSpriteSurface)
    cerr << "Sprite error: Sprite not initialized\n" << endl;
  SDL_Rect dstRect;
  dstRect.x = x - SPRITE_SIZE_X/2;
  dstRect.y = y + PLAYER_HEIGHT - SPRITE_SIZE_Y;
  dstRect.w = Frame.w;
  dstRect.h = Frame.h;
  if (!bShadow) {
    nResult = SDL_BlitSurface(pSpriteSurface, &Frame, dst, &dstRect);
  } else {
    nResult = SDL_BlitSurface(pShadowSurface, &Frame, dst, &dstRect);
  }
  return nResult;
}

int Sprite::Draw(int animationIndex, int frameIndex, SDL_Surface *dst, int x, int y, bool bShadow) {
  Frame.x = Frame.w * frameIndex;
  Frame.y = Frame.h * animationIndex;
  return Blit(dst, x, y, bShadow);
}

Sprite::~Sprite() {
  if (SpriteImageFile) delete[] SpriteImageFile;
  if (pSpriteSurface) SDL_FreeSurface(pSpriteSurface);
  if (ShadowImageFile) delete[] ShadowImageFile;
  if (pShadowSurface) SDL_FreeSurface(pShadowSurface);
}
